﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Security.Cryptography.X509Certificates;
using System.Configuration;
using AgnisDAL.AGNIS_FORMSDataSetTableAdapters;


namespace AgnisDAL
{   
    /// <summary>
    /// This Class will load an agnis form object (from AgnisTranslator project) to the staging database
    /// </summary>
    public class cAgnisDAL
    {
        #region local members
        private static String agnisFormsConnectionString;
        private static System.Data.SqlClient.SqlConnection mySqlConnection;
        private static AgnisDAL.AGNIS_FORMSDataSet dsAgnisDb = new AgnisDAL.AGNIS_FORMSDataSet();
        static QueriesTableAdapter qAdapter = new QueriesTableAdapter();
        //Create and instanciate the table adapter 'frevisionTa'
        static FORM_REVISIONTableAdapter frevisionTa= new FORM_REVISIONTableAdapter();
        static MODULETableAdapter ModuleTA = new MODULETableAdapter();
        static PROCESSING_STATUSTableAdapter ProcessingStatusTa = new PROCESSING_STATUSTableAdapter();
        static INFORMATION_PROCESSTableAdapter InfoProcessTa = new INFORMATION_PROCESSTableAdapter();
        static GENERATED_FORMS_LIST_WITH_STATUSTableAdapter GeneratedFormsListTa = new GENERATED_FORMS_LIST_WITH_STATUSTableAdapter();
        static FORMTableAdapter FormTa = new FORMTableAdapter();
        static QUESTIONTableAdapter QuestionTA = new QUESTIONTableAdapter();
        //Those Boolean variables indicate if the 'calculated' value already exist.
        static bool bFormRevisionExist, 
                    bFormExist, 
                    bModuleExist, 
                    bFormElementErrorExist, 
                    bQuestionExist, 
                    bProcessingStatusExist,
                    bInformationProcess;
        static int  iSequenceFormRevNumber = 0;
        #endregion

        public static void SetConnectionString(String cString)
        {
            agnisFormsConnectionString = cString;
            mySqlConnection = new SqlConnection(agnisFormsConnectionString);
            qAdapter.SetConnection(mySqlConnection);
            frevisionTa.Connection = mySqlConnection;
            ProcessingStatusTa.Connection = mySqlConnection;
            InfoProcessTa.Connection = mySqlConnection;
        }
        public static bool LoadAgnisStagingDb(AGNIS_FORMSDataSet dsAgnisStagingDb)
        {

            GeneratedFormsListTa.Connection = mySqlConnection;
            frevisionTa.Connection = mySqlConnection;
            FormTa.Connection = mySqlConnection;
            //Load the dataset
            GeneratedFormsListTa.Fill(dsAgnisStagingDb.GENERATED_FORMS_LIST_WITH_STATUS);
            frevisionTa.Fill(dsAgnisStagingDb.FORM_REVISION);
            FormTa.Fill(dsAgnisStagingDb.FORM);
            return true;
        }
        #region 'IF EXIST' Functions

        private static void FormRevisionExist(int formRevisionID)
        {
            if (qAdapter.FormRevisionIDExist(formRevisionID) != null)
            {
                bFormRevisionExist = true;
            }
            else
            {
                bFormRevisionExist = false;
            }
        }

        private static void FormExist(int formID)
        {
            if (qAdapter.FormIDExist(formID) != null)
            {
                bFormExist = true;
            }
            else
            {
                bFormExist = false;
            }
        }
        /// <summary>
        /// Check even any Module ID refering to the FormRevisionID already exists
        /// </summary>
        /// <param name="ModuleID"></param>
        /// <param name="FormRevisionID"></param>
        private static void ModuleRefersToFormRevisionExist(int ModuleID, int FormRevisionID)
        {
            if (qAdapter.ModuleIDExist(ModuleID, FormRevisionID) != null)
            {
                bModuleExist = true;
            }
            else
            {
                bModuleExist = false;
            }
        }
        /// <summary>
        /// Check even question ID already exist into a module
        /// </summary>
        /// <param name="QuestionID"></param>
        private static void QuestionExist(int QuestionID, int ModuleID)
        {
            if (qAdapter.QuestionIDExist(QuestionID, ModuleID) != null)
            {
                bModuleExist = true;
            }
            else
            {
                bModuleExist = false;
            }
        }
        /// <summary>
        /// Check even FORM ELEMENT ERROR already exist in the database
        /// </summary>
        /// <param name="FormElementErrorId"></param>
        private static void FormElementErrorExist(int FormElementErrorId)
        {
            if (qAdapter.FormElementErrorIDExist(FormElementErrorId) != 0)
            {
                bFormElementErrorExist = true;
            }
            else
            {
                bFormElementErrorExist = false;
            }
        }

        /// <summary>
        /// Check even processing status ID already exist
        /// </summary>
        /// <param name="ProcessungStatusId"></param>
        /// <param name="FormRevisionID"></param>
        private static void ProcessingStatusExist(int ProcessungStatusId, int FormRevisionID)
        {
            if (qAdapter.ProcessingStatusIDExist((long)ProcessungStatusId, (long)FormRevisionID) != 0)
            {
                bProcessingStatusExist = true;
            }
            else
            {
                bProcessingStatusExist = false;
            }
        }
        /// <summary>
        /// Check even information process ID already exist
        /// </summary>
        /// <param name="InformationProcessId"></param>
        private static void InformationProcessExist(int InformationProcessId)
        {
            if (qAdapter.InformationProcessIDExist(InformationProcessId) != 0)
            {
                bInformationProcess = true;
            }
            else
            {
                bInformationProcess = false;
            }
        }
        #endregion

        #region LOADING Data  Functions

        /// <summary>
        /// load Form_Revision into Agnis staging DB then into historic table
        /// </summary>
        /// <param name="frevision"></param>
        /// <param name="myFormNumber"></param>
        /// <param name="myFormPublicID"></param>
        public  static void SendFormRevisionToDB(ServiceAgnis.FormRevision frevision, int myFormNumber, long myFormPublicID, int visit_id, int id, int idaa, DateTime dateOfTransplant)
        {
            if (isFormRevisionDataLoaded(frevision, myFormNumber, myFormPublicID, visit_id, id, idaa, dateOfTransplant))
            {
                //fill GENERATED FORM LIST table
                SaveFormIntoGeneratedFormsList(frevision, myFormNumber, visit_id, id, idaa, dateOfTransplant);                 
            }
            
            
        }

        public static bool isFormRevisionDataLoaded(ServiceAgnis.FormRevision frevision, int myFormNumber, long myFormPublicID, int visit_id, int id, int idaa, DateTime dateOfTransplant)
        {
            try
            {
                if (myFormNumber == 240000000) // as 2400 doesn't exist yet
                {
                    //on crèe un objet plus typé "objet-ligne" à partir d'une nouvelle ligne de la table form_revision (du ds)
                    AgnisDAL.AGNIS_FORMSDataSet.FORM_REVISIONRow fRevisionRow = dsAgnisDb.FORM_REVISION.NewFORM_REVISIONRow();
                    //Retrieve the value of each data                   
                    fRevisionRow.FORM_REVISION_ID = 1;
                    fRevisionRow.FORM_ID = 1;
                    fRevisionRow.FORM_REVISION_SEQ_NUM = (int)1;
                    //frevision.form.currentFormRevisionSequenceNumber = Convert.ToString(fRevisionRow.FORM_REVISION_SEQ_NUM);
                    iSequenceFormRevNumber = fRevisionRow.FORM_REVISION_SEQ_NUM;
                    //Add this row to FormRevision
                    dsAgnisDb.FORM_REVISION.AddFORM_REVISIONRow(fRevisionRow);
                    //Update the 'frevisionTa'
                    frevisionTa.Update(dsAgnisDb.FORM_REVISION);
                    return true;
                }
                else
                {
                    //on crèe un objet plus typé "objet-ligne" à partir d'une nouvelle ligne de la table form_revision (du ds)
                    AgnisDAL.AGNIS_FORMSDataSet.FORM_REVISIONRow fRevisionRow = dsAgnisDb.FORM_REVISION.NewFORM_REVISIONRow();
                    //Retrieve the value of each data
                    frevision.formId = GenerateFormID(); // ?
                    frevision.form.id = frevision.formId;


                    fRevisionRow.FORM_REVISION_ID = frevision.id;
                    fRevisionRow.FORM_ID = (int)frevision.formId;
                    fRevisionRow.FORM_REVISION_SEQ_NUM = (int)1;
                    frevision.form.currentFormRevisionSequenceNumber = Convert.ToString(fRevisionRow.FORM_REVISION_SEQ_NUM);
                    //fRevisionRow.MODIFICATION_TIME = Convert.ToDateTime("18/12/2010"); //test value
                    iSequenceFormRevNumber = fRevisionRow.FORM_REVISION_SEQ_NUM;
                    //Add this row to FormRevision
                    dsAgnisDb.FORM_REVISION.AddFORM_REVISIONRow(fRevisionRow);
                    //Update the 'frevisionTa'
                    frevisionTa.Update(dsAgnisDb.FORM_REVISION);
                    //Fill FORM Table
                    SendFormToDB(frevision.form);
                    //Fill MODULE table
                    SendModule(frevision, (int)fRevisionRow.FORM_REVISION_ID);
                    //Fill FORM ELEMENT ERROR table
                    SendFormElementError(frevision);
                   
                    //fill INFORMATION PROCESS table
                    int iRank = 0;
                    switch (myFormNumber)
                    {
                        case 2400: iRank = 1; break;
                        case 2450: iRank = 2; break;
                        case 2900: iRank = 3; break;
                        default: break;

                    }
                    int infoProcessId = SendInformationProcess(iRank);
                    SendProcessingStatus(frevision, (int)fRevisionRow.FORM_REVISION_ID, myFormNumber, infoProcessId);
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error at SendFormRevisionToDB() function", ex);
            }
        }
        public static bool SaveFormIntoGeneratedFormsList(ServiceAgnis.FormRevision frevision, int myFormNumber,int visitId, int id,int idaa,DateTime dateOfTransplant)
        {
            try
            {                
                AgnisDAL.AGNIS_FORMSDataSet.GENERATED_FORMS_LIST_WITH_STATUSRow GFormListRow = dsAgnisDb.GENERATED_FORMS_LIST_WITH_STATUS.NewGENERATED_FORMS_LIST_WITH_STATUSRow();
                GFormListRow.FORM_ID = frevision.formId;
                GFormListRow.FORM_REVISION_ID = frevision.id;
                GFormListRow.FORM_NUMBER = myFormNumber;
                GFormListRow.VISIT_ID = visitId;
                //GFormListRow.CRID = 0;
                GFormListRow.ID = id;
                GFormListRow.IDAA = idaa;
                GFormListRow.DATE_OF_HSCT = dateOfTransplant;
                GFormListRow.STATUS = "";
                GFormListRow.CRID = 0;
                DateTime modificationTimeIsNow = DateTime.Now.Date; //will be the EBMT_LAST_MOD_TIME but should be other
                GFormListRow.EBMT_LAST_MOD_TIME = modificationTimeIsNow;
                dsAgnisDb.GENERATED_FORMS_LIST_WITH_STATUS.AddGENERATED_FORMS_LIST_WITH_STATUSRow(GFormListRow);
                
                GeneratedFormsListTa.Fill(dsAgnisDb.GENERATED_FORMS_LIST_WITH_STATUS);
                
                //GFLta.Fill(dsAgnisDb.GENERATED_FORMS_LIST_WITH_STATUS);
                
                return true;
               
            }
            catch (Exception ex )
            {
                throw new Exception("Error at SaveFormIntoGeneratedFormsList() function", ex);                
            }
            
        }
        /// <summary>
        /// Sending a processus status data
        /// </summary>
        /// <param name="fRevision"></param>
        /// <param name="FormRevisionID"></param>
        public static void SendProcessingStatus(ServiceAgnis.FormRevision fRevision, int FormRevisionID, int FormNumber, int InfoProcessID)
        {
            int iRank = 0;
            switch (FormNumber)
            {
                case 2400: iRank = 1; break;
                case 2450: iRank = 2; break;
                default: break;
            }

            ProcessingStatusExist(GenerateProcessingStatusID(), FormRevisionID);
            if (!bProcessingStatusExist)
            {
                //create a specific typed row
                AgnisDAL.AGNIS_FORMSDataSet.PROCESSING_STATUSRow ProcessStatusRow = dsAgnisDb.PROCESSING_STATUS.NewPROCESSING_STATUSRow();
                //Retrieve the value of each data col
                ProcessStatusRow.PROCESSING_STATUS_ID = GenerateProcessingStatusID();
                ProcessStatusRow.INFORMATION_PROCESS_ID = InfoProcessID;
                ProcessStatusRow.FORM_REVISION_ID = FormRevisionID;
                ProcessStatusRow.PROCESSING_RANK = iRank;
                //ProcessStatusRow.PARENT_PROCESSING_STATUS_ID = ? 
                ProcessStatusRow.VALUE = "READY";
                //
                dsAgnisDb.PROCESSING_STATUS.AddPROCESSING_STATUSRow(ProcessStatusRow);
                ProcessingStatusTa.Update(dsAgnisDb.PROCESSING_STATUS);
                
            }
        }
        public static int SendInformationProcess(int iRankInfo)
        {
            InformationProcessExist(GenerateInfoProcessID());
            if (!bInformationProcess)
            {
                //create a specific typed row
                AgnisDAL.AGNIS_FORMSDataSet.INFORMATION_PROCESSRow InfoProcessRow = dsAgnisDb.INFORMATION_PROCESS.NewINFORMATION_PROCESSRow();
                //Retrieve the value of each col
                InfoProcessRow.INFORMATION_PROCESS_ID = GenerateInfoProcessID();
                InfoProcessRow.UNIQUE_NAME = Convert.ToString(InfoProcessRow.INFORMATION_PROCESS_ID);
                InfoProcessRow.PROCESS_TYPE = "SUBMIT";
                InfoProcessRow.PROCESS_STATUS = "READY";
                InfoProcessRow.PROCESSING_RANK = iRankInfo;
                //
                dsAgnisDb.INFORMATION_PROCESS.AddINFORMATION_PROCESSRow(InfoProcessRow);
                InfoProcessTa.Update(dsAgnisDb.INFORMATION_PROCESS);
                return (int)InfoProcessRow.INFORMATION_PROCESS_ID;
            }
            return -1;
        }

        /// <summary>
        /// Store a Form
        /// </summary>
        /// <param name="Frm"></param>
        public static void SendFormToDB(ServiceAgnis.Form Frm)
        {
            int i = (int)Frm.id;
            FormExist(i);
            //If the Form row does not exist yet, we save it

            if (!bFormExist)
            {
                //Create a specific typed row from the ds FORM table rows
                AgnisDAL.AGNIS_FORMSDataSet.FORMRow fRow = dsAgnisDb.FORM.NewFORMRow();
                fRow.FORM_ID = i;
                fRow.PUBLISHER_INSTITUTION_ID = (int)Frm.publisherInstitutionId;
                fRow.INSTANCE_ID = Frm.instanceId;
                fRow.ORIGINATOR_INSTITUTION_ID = (int)1;//We need to change that in order to take the right INStit_ID
                fRow.PUBLIC_ID = (int)Frm.publicId;
                fRow.VERSION = Frm.version;
                fRow.CURRENT_FORM_REVISION_SEQ_NUM = Convert.ToInt32(Frm.currentFormRevisionSequenceNumber);
                if (Frm.modificationTime!= Convert.ToDateTime("01/01/0001 00:00:00"))
                {
                    fRow.MODIFICATION_TIME = Frm.modificationTime;
                }
                
                //on ajoute la-dite ligne à la form_revision
                dsAgnisDb.FORM.AddFORMRow(fRow);
                
                //Attention la colonne Form_ID est Identity = true                   
                FormTa.Update(dsAgnisDb.FORM);


                //AgnisDAL.AGNIS_FORMSDataSet.FORMRow fRow = dsAgnisDb.FORM.NewFORMRow();
                //fRow.FORM_ID = 54321;
                //fRow.PUBLISHER_INSTITUTION_ID = 12345;
                //fRow.INSTANCE_ID = "001";
                //fRow.ORIGINATOR_INSTITUTION_ID = 12345;
                //fRow.PUBLIC_ID = 12345;
                //fRow.VERSION = Frm.version;
                //fRow.CURRENT_FORM_REVISION_SEQ_NUM = 123;
                //fRow.MODIFICATION_TIME = DateTime.Now;
                ////on ajoute la-dite ligne à la form_revision
                //dsAgnisDb.FORM.AddFORMRow(fRow);
                ////on crèe et instancie la Table Adapter
                //AgnisDAL.AGNIS_FORMSDataSetTableAdapters.FORMTableAdapter frTa = new AgnisDAL.AGNIS_FORMSDataSetTableAdapters.FORMTableAdapter();
                ////Attention la colonne Form_ID est Identity = true                   
                //frTa.Update(dsAgnisDb.FORM);
            }
            else
            {
                //there is already a form with the same ID
            }

        }


        /// <summary>
        /// Sending ModuleCollection []
        /// </summary>
        /// <param name="fRevision"></param>
        /// <param name="Identifiant_FormRevision"></param>
        public static void SendModule(ServiceAgnis.FormRevision fRevision, int Identifiant_FormRevision)
        {
            fRevision.moduleCollection = fRevision.moduleCollection.ToArray<AgnisDAL.ServiceAgnis.Module>();
            int iCountModule = fRevision.moduleCollection.Count();//just for test
            //Boucle sur la taille du tableau (=nombre d'instance de modules)
            foreach (AgnisDAL.ServiceAgnis.Module ResultModuleInstanceToInsert in fRevision.moduleCollection)
            {
                ModuleRefersToFormRevisionExist(GenerateModuleID(), (int)fRevision.id);
                //Y a-t-il au moins un module associé à la FORM_REVISION ?
                if (!bModuleExist)
                {// If NOT , insert
                    AgnisDAL.AGNIS_FORMSDataSet.MODULERow ModuleRow = dsAgnisDb.MODULE.NewMODULERow();
                    //Retrieve the value of each data table
                    ModuleRow.MODULE_ID = GenerateModuleID();
                    ModuleRow.FORM_REVISION_ID = Identifiant_FormRevision;
                    ModuleRow.PUBLIC_ID = ResultModuleInstanceToInsert.publicId;
                    ModuleRow.VERSION = ResultModuleInstanceToInsert.version;
                    ModuleRow.REPEAT_SEQUENCE_NUMBER = Convert.ToInt16(ResultModuleInstanceToInsert.repeatSequenceNumber);
                    if (fRevision.modificationTime != Convert.ToDateTime("01/01/0001 00:00:00"))
                    { 
                        ModuleRow.MODIFICATION_TIME = fRevision.modificationTime; 
                    }
                    //on ajoute la-dite ligne à la form_revision                    
                    dsAgnisDb.MODULE.AddMODULERow(ModuleRow);
                    //on crèe et instancie la Table Adapter
                    //AgnisDAL.AGNIS_FORMSDataSetTableAdapters.MODULETableAdapter ModuleTA = new AgnisDAL.AGNIS_FORMSDataSetTableAdapters.MODULETableAdapter();
                    //                
                    ModuleTA.Update(dsAgnisDb.MODULE);
                    SendQuestion(ResultModuleInstanceToInsert, (int)ModuleRow.MODULE_ID);
                }
            }


        }

        /// <summary>
        /// Sending Question belonging to a module
        /// </summary>
        /// <param name="ModuleSent"></param>
        /// <param name="ModuleID"></param>
        public static void SendQuestion(ServiceAgnis.Module ModuleSent, int ModuleID)
        {
            ModuleSent.questionCollection = ModuleSent.questionCollection.ToArray<AgnisDAL.ServiceAgnis.Question>();
            int iCountQuestion = ModuleSent.questionCollection.Count();//just for test
            //
            foreach (AgnisDAL.ServiceAgnis.Question ResultQuestionToInsert in ModuleSent.questionCollection)
            {
                QuestionExist(GenerateQuestionID(), ModuleID);
                if (!bQuestionExist)
                {
                    AgnisDAL.AGNIS_FORMSDataSet.QUESTIONRow QuestionRow = dsAgnisDb.QUESTION.NewQUESTIONRow();
                    //Retrive the value of each data
                    QuestionRow.QUESTION_ID = GenerateQuestionID();
                    QuestionRow.MODULE_ID = ModuleID;
                    QuestionRow.DATA_ELEMENT_PUBLIC_ID = ResultQuestionToInsert.dataElementPublicId;
                    QuestionRow.DATA_ELEMENT_VERSION = ResultQuestionToInsert.dataElementVersion;
                    //QuestionRow.ALTERNATE_METADATA_TYPE = ResultQuestionToInsert.alternateMetadataType;
                    //QuestionRow.ALTERNATE_METADATA_ID = ResultQuestionToInsert.alternateMetadataId;
                    QuestionRow.VALUE = ResultQuestionToInsert.value;
                    QuestionRow.ALTERNATE_VALUE = ResultQuestionToInsert.alternateValue;
                    QuestionRow.ERROR_EXCEPTION = ResultQuestionToInsert.errorException;
                    QuestionRow.DELETE_FLAG = Convert.ToByte(ResultQuestionToInsert.delete);
                    QuestionRow.VALUE_MEANING_PUBLIC_ID = ResultQuestionToInsert.valueMeaningPublicId;
                    QuestionRow.VALUE_MEANING_VERSION = ResultQuestionToInsert.valueMeaningVersion;
                    if (ResultQuestionToInsert.modificationTime != Convert.ToDateTime("01/01/0001 00:00:00"))
                    {
                        QuestionRow.MODIFICATION_TIME = ResultQuestionToInsert.modificationTime;
                    }
                    //QuestionRow.MODIFICATION_USER_ID = ResultQuestionToInsert.modificationUserId;
                    dsAgnisDb.QUESTION.AddQUESTIONRow(QuestionRow);
                    //AgnisDAL.AGNIS_FORMSDataSetTableAdapters.QUESTIONTableAdapter QuestionTA = new AgnisDAL.AGNIS_FORMSDataSetTableAdapters.QUESTIONTableAdapter();
                    QuestionTA.Update(dsAgnisDb.QUESTION);
                }
            }
        }





        /// <summary>
        /// Sending FORM ELEMENT ERROR 
        /// </summary>
        public static void SendFormElementError(ServiceAgnis.FormRevision fRevision)
        {

            if (fRevision.errorCollection != null)
            {
                fRevision.errorCollection = fRevision.errorCollection.ToArray<AgnisDAL.ServiceAgnis.FormElementError>();
                int iCountElementError = fRevision.errorCollection.Count();//just for test

                //boucle sur le tableau FormElementErrorCollection
                foreach (AgnisDAL.ServiceAgnis.FormElementError resultFormElementErrorToInsert in fRevision.errorCollection)
                {
                    //Generate the FormElementErrorID
                    int _FormElementErrorID = GenerateFormElementErrorID();
                    FormElementErrorExist(_FormElementErrorID);
                    if (!bFormElementErrorExist)
                    {
                        //Create a specific row
                        AgnisDAL.AGNIS_FORMSDataSet.FORM_ELEMENT_ERRORRow FormElementErrorRow = dsAgnisDb.FORM_ELEMENT_ERROR.NewFORM_ELEMENT_ERRORRow();
                        //Retrieve the value of each data
                        FormElementErrorRow.FORM_ELEMENT_ERROR_ID = _FormElementErrorID;
                        FormElementErrorRow.FORM_REVISION_ID = resultFormElementErrorToInsert.formRevisionId;
                        FormElementErrorRow.QUESTION_ID = resultFormElementErrorToInsert.questionId;
                        FormElementErrorRow.ERROR_TYPE = resultFormElementErrorToInsert.type;
                        FormElementErrorRow.ERROR_MESSAGE = resultFormElementErrorToInsert.message;
                        FormElementErrorRow.ERROR_RAW_DATA = resultFormElementErrorToInsert.rawData;
                        //FormElementErrorRow.MODIFICATION_TIME = resultFormElementErrorToInsert.modificationTime;
                        //FormElementErrorRow.MODIFICATION_USER_ID = resultFormElementErrorToInsert.modificationUserId;
                        dsAgnisDb.FORM_ELEMENT_ERROR.AddFORM_ELEMENT_ERRORRow(FormElementErrorRow);
                        AgnisDAL.AGNIS_FORMSDataSetTableAdapters.FORM_ELEMENT_ERRORTableAdapter FormElementErrorTA = new AgnisDAL.AGNIS_FORMSDataSetTableAdapters.FORM_ELEMENT_ERRORTableAdapter();
                        FormElementErrorTA.Update(dsAgnisDb.FORM_ELEMENT_ERROR);
                    }
                    else
                    {
                        //nothing 
                    }
                }
            }
        }

        #endregion

        #region ID GENERATION functions

        /// <summary>
        /// Increment the value ID of FormRevision
        /// </summary>
        /// <returns></returns>
        private static int GenerateFormRevisionID()
        {           
            try
            {
                int countFrmRev = 0;
                if ((object)qAdapter.CountLastFormRevision() != null)
                {
                    countFrmRev = Convert.ToInt32(qAdapter.CountLastFormRevision());
                }
                return countFrmRev + 1;
            }
            catch (Exception ex)
            {
                throw new Exception("Error at Generation ID", ex);
            }
        }

        /// <summary>
        /// Increment the value ID of Form
        /// </summary>
        /// <returns></returns>
        private static int GenerateFormID()
        {
            
            try
            {
                int countFrm = 0;
                if ((object)qAdapter.CountLastForm() != null)
                {
                    countFrm = Convert.ToInt32(qAdapter.CountLastForm());
                }
                return countFrm + 1;
            }
            catch (Exception ex)
            {
                throw new Exception("Error at Generation ID", ex);
            }
        }

        /// <summary>
        /// Increment the ID value of the module ID
        /// </summary>
        /// <param name="FrevisionID"></param>
        /// <returns></returns>
        private static int GenerateModuleID()
        {
            try
            {
                int CountModuleFormRevision = 0;
                if ((object)qAdapter.CountLastModuleFormRevision() != null)
                {
                    CountModuleFormRevision = Convert.ToInt32(qAdapter.CountLastModuleFormRevision());
                }
                return CountModuleFormRevision + 1;
            }
            catch (Exception ex)
            {
                throw new Exception("Error at Generation ID", ex);
            }
        }

        /// <summary>
        /// Increment the ID value of FormElementErrorID
        /// </summary>
        /// <returns></returns>
        private static int GenerateFormElementErrorID()
        {
            int countFrmElementErrID = (int)qAdapter.CountFormElementError();
            return countFrmElementErrID + 1;
        }
        /// <summary>
        /// Increment Question ID value
        /// </summary>
        /// <returns></returns>
        private static int GenerateQuestionID()
        {
            int countQuestionID = (int)qAdapter.CountQuestion();
            return countQuestionID + 1;
        }
        /// <summary>
        /// Increment ProcessusStatus ID value
        /// </summary>
        /// <returns></returns>
        private static int GenerateProcessingStatusID()
        {
            int countPrStatus = (int)qAdapter.CountProcessingStatus();
            return countPrStatus + 1;
        }

        private static int GenerateInfoProcessID()
        {
            int countInfoProcess = (int)qAdapter.CountInfoProcess();
            return countInfoProcess + 1;
        }
        #endregion

        public static ServiceAgnis.FormRevision SendFormRevision(AgnisDAL.ServiceAgnis.FormRevision myGeneratedFormRevision)
        {
            AgnisDAL.ServiceAgnis.FormRevision reslt = new AgnisDAL.ServiceAgnis.FormRevision();
            AgnisDAL.ServiceAgnis.FormHandlerService agnis_services = new AgnisDAL.ServiceAgnis.FormHandlerService();

            X509Certificate2 x509 = new X509Certificate2(AgnisDAL.Properties.Settings.Default.AgnisCertificatesLocation + @"\" + AgnisDAL.Properties.Settings.Default.AgnisCertificatesFilename, AgnisDAL.Properties.Settings.Default.AgnisCertificatesPwd);
            agnis_services.ClientCertificates.Add(x509);
            AgnisDAL.ServiceAgnis.SubmitFormRevisionRequestFormRevision formRevisionReq = new AgnisDAL.ServiceAgnis.SubmitFormRevisionRequestFormRevision();
            formRevisionReq.FormRevision = myGeneratedFormRevision;
            // "https://yew.nmdp.org:18443/wsrf/services/agnis/FormHandler";
            agnis_services.Url = AgnisDAL.Properties.Settings.Default.AgnisDAL_AgnisService_FormHandlerService;
            reslt = agnis_services.submitFormRevision(formRevisionReq);
            return reslt;
        }
    }
}
